﻿using Android;
﻿﻿﻿﻿﻿using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using AndroidX.Core.App;
using AndroidX.Core.Content;

namespace MauiBuilder
{
    [Activity(Theme = "@style/Maui.SplashTheme", 
        MainLauncher = true, 
        LaunchMode = LaunchMode.SingleTop, 
        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density,
        Exported = true)]
    public class MainActivity : MauiAppCompatActivity
    {
        protected override void OnCreate(Bundle? savedInstanceState)
        {
            //全透明任务栏
            Window.SetFlags(Android.Views.WindowManagerFlags.TranslucentNavigation, Android.Views.WindowManagerFlags.TranslucentNavigation);
            //设置状态栏，导航样颜色为透明
            Window.SetStatusBarColor(Android.Graphics.Color.Transparent);
            Window.SetNavigationBarColor(Android.Graphics.Color.Transparent);

            base.OnCreate(savedInstanceState);
            
            // 检查和请求通知权限
            CheckAndRequestNotificationPermission();
            
            // 自动启动前台服务
            StartForegroundServiceAutomatically();

            // 检查是否是重启启动
            CheckRestartIntent(savedInstanceState, Intent);
        }
        
        private void CheckAndRequestNotificationPermission()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
            {
                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.PostNotifications) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.PostNotifications }, 1001);
                }
            }
        }
        
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            
            if (requestCode == 1001)
            {
                if (grantResults.Length > 0 && grantResults[0] == Permission.Granted)
                {
                    // 权限已授予
                    Services.LogManager.Instance.LogInfo("通知权限已授予");
                    // 权限授予后再次尝试启动前台服务
                    StartForegroundServiceAutomatically();
                }
                else
                {
                    // 权限被拒绝
                    Services.LogManager.Instance.LogInfo("通知权限被拒绝");
                }
            }
        }

        private void CheckRestartIntent(Bundle savedInstanceState, Intent intent)
        {
            try
            {
                // 检查重启标志
                if (intent?.HasExtra("RESTART_REASON") == true)
                {
                    var reason = intent.GetStringExtra("RESTART_REASON");
                    Services.LogManager.Instance.LogInfo($"应用通过重启启动，原因: {reason}");

                    // 可以在这里执行重启后的初始化逻辑
                }

                // 检查是否是从最近任务启动
                if ((intent?.Flags & ActivityFlags.LaunchedFromHistory) != 0)
                {
                    Services.LogManager.Instance.LogInfo("从最近任务启动");
                }
            }
            catch (Exception ex)
            {
                Services.LogManager.Instance.LogError($"检查重启 Intent 失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 自动启动前台服务
        /// </summary>
        private void StartForegroundServiceAutomatically()
        {
            try
            {
                Services.LogManager.Instance.LogInfo("尝试自动启动前台服务");
                
                var serviceIntent = new Android.Content.Intent(this, typeof(Platforms.Android.ForegroundService));
                
                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    StartForegroundService(serviceIntent);
                }
                else
                {
                    StartService(serviceIntent);
                }
                
                Services.LogManager.Instance.LogInfo("前台服务自动启动成功");
            }
            catch (Exception ex)
            {
                Services.LogManager.Instance.LogError($"自动启动前台服务失败：{ex.Message}");
            }
        }
    }
}
